using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Serialization;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Input.Touch;
using System.Threading;
using System.IO.IsolatedStorage;
using System.IO;


namespace ebookreader
{
    public struct Book
    {
        public String title;
        //public List<String> authors;
        public DateTime lastRead;
        public int page;
        public int total_pages;
        public String filename;

    }


  public class TitleList : Menu
  {
    #region Fields
    static readonly int MARGIN = 5;
    GraphicsDeviceManager graphics;
    
    SpriteFont font;
    //SpriteBatch sprite_batch;
    Vector2 position = new Vector2(MARGIN, MARGIN);



    List<Book> books;
    List<BoxedLabelScrollableButton> books_buttons = new List<BoxedLabelScrollableButton>();
    #endregion


    public TitleList(Game game, SpriteFont font)
      : base(game)
    {
      this.font = font;

      

      //UpdateOrder = (int)screenorder.reader;
      //draworder = (int)screenOrder.Reader;

      //game.Exiting += new EventHandler<EventArgs>(SaveState);
    }

    public override void Initialize()
    {

        Game.Components.Add(new InputManager(Game));
        sprite_batch = Game.Services.GetService(typeof(SpriteBatch)) as SpriteBatch;
        input_manager = Game.Services.GetService(typeof(IInputManager)) as IInputManager;
        input_manager.OnTap += new InputManager.Tap(OnTap);
        base.Initialize();
    }

    protected override void LoadContent()
    {


      Texture2D ui_button_dock = Game.Content.Load<Texture2D>("Textures/UI/title");

      sprite_batch = Game.Services.GetService(typeof(SpriteBatch)) as SpriteBatch;
      graphics = Game.Services.GetService(typeof(GraphicsDeviceManager)) as GraphicsDeviceManager;


        //foreach (var file in Directory.GetFiles(Game.Content.RootDirectory+"\\Ebooks").Where(s => s.EndsWith(".txt")))
        //{
        //    TitleContainer.OpenStream(file);
        //}

      books = loadBooks();
      
      //var c = books.Count;

        int i=0;
      foreach (var book in books)
      {
          var nb = new BoxedLabelScrollableButton(sprite_batch, ui_button_dock, new Vector2(MARGIN, MARGIN + i * 135), 
              font, new Vector2(0, 0),book.title+".........................." , Color.White, Color.Black);
          nb.OnPress += new Press((MenuEntry m) => { ScreenManager.StartBookReader(Game, font, @"Content/Ebooks/" + book.filename); });
          books_buttons.Add(nb);
          entries.Add(nb);
          i++;
      }
       
        


      //input_manager.OnHorizontalFlick += new InputManager.Flick(OnFlick);



      //  //PROVA
      //input_manager.OnVerticalDrag += new InputManager.Drag(OnDrag);
      //input_manager.OnDragCompleted += new InputManager.DragCompleted(OnDragCompleted);
      input_manager.OnDoubleTap += new InputManager.Tap((v) => 
          SaveNewBook(books, new Book() { filename = "0.txt", lastRead = DateTime.MinValue, page = 0, title = "second bookla casa nella \nroccia di peter anderson end co", total_pages = 1000 }) );
      graphics.SetLandscapeRightOrientation();

      
      //RestoreState();

      base.LoadContent();
    }

    protected override void Dispose(bool disposing)
    {
        //input_manager.OnHorizontalFlick -= new InputManager.Flick(OnFlick);
        //input_manager.OnVerticalDrag -= new InputManager.Drag(OnDrag);
        //input_manager.OnDragCompleted -= new InputManager.DragCompleted(OnDragCompleted);
        //if (input_manager != null)
        //    input_manager.OnPress -= new InputManager.Tap(OnTap);
        Game.Services.RemoveService(typeof(IInputManager));

        graphics.SetLandscapeLeftOrientation();

        base.Dispose(disposing);
    }

    public override void Update(GameTime gameTime)
    {

        if (!dragging)
        {
            position.Y += force;
            if (force != 0.0f)
                force = MathHelper.Lerp(force, 0.0f, (float)gameTime.ElapsedGameTime.TotalSeconds * (50 / Math.Abs(force)));
            if (Vector2.Distance(position, new Vector2(MARGIN, MARGIN)) > 0.0f)
                position = Vector2.Lerp(position, new Vector2(MARGIN, MARGIN), (float)gameTime.ElapsedGameTime.TotalSeconds * 5);
            //}
            //else
            //{
        }
        if (position.Y < -GraphicsDevice.Viewport.Height / 2)
            if (current_page >= pages.Count)
                position = new Vector2(MARGIN, GraphicsDevice.Viewport.Height / 2);
            else
            {
                current_page++;
                position = position + new Vector2(0, GraphicsDevice.Viewport.Height);
            }
        else if (position.Y > GraphicsDevice.Viewport.Height / 2)
            if (current_page < 1)
                position = new Vector2(MARGIN, GraphicsDevice.Viewport.Height / 2);
            else
            {
                current_page--;
                position = position - new Vector2(0, GraphicsDevice.Viewport.Height);
            }



        if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
        {
            OptionsMenu.SaveSavedOptions(savedOptions);
            ScreenManager.SelectMainMenu(Game);
            return;
        }


        base.Update(gameTime);
    }

    public override void Draw(GameTime gameTime)
    {
      sprite_batch.Begin();
      //sprite_batch.DrawString(font, ""+current_page, Vector2.Zero, Color.Red);
      //if (current_page >= pages.Count)
      //{
      //    var dots = ".";
      //    for (int i = 0; i < gameTime.TotalGameTime.Seconds % 3; i++)
      //    {
      //        dots += ".";
      //    }
      //    sprite_batch.DrawString(font, "Loading" + dots, new Vector2(50, 50), Color.CornflowerBlue);
      //}
      //else
      //{
      //    if(current_page>0)
      //      sprite_batch.DrawString(font, pages[current_page-1], position - new Vector2(0,GraphicsDevice.Viewport.Height), Color.CornflowerBlue);
      //    sprite_batch.DrawString(font, pages[current_page], position, Color.CornflowerBlue);
      //    if (current_page < pages.Count)
      //      sprite_batch.DrawString(font, pages[current_page+1], position + new Vector2(0, GraphicsDevice.Viewport.Height), Color.CornflowerBlue);

      //}

      //int i = 0;
      //foreach (var book in books)
      //{
      //    sprite_batch.DrawString(font, book.title, position + new Vector2(0, i*30), Color.CornflowerBlue);
      //    i++;
      //}

      sprite_batch.End();

      base.Draw(gameTime);
    }




    private List<Book> loadBooks()
    {
#if WINDOWS_PHONE
        IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication();
        IsolatedStorageFileStream stream;
        try
        {
            stream = store.OpenFile("list.xml", FileMode.Open, FileAccess.ReadWrite);
        }
        catch (Exception)
        {
            store.Dispose();
            return new List<Book>();
        }
#else
			FileStream stream = File.Open(FileName, FileMode.Create);			
#endif

        XmlSerializer serializer = new XmlSerializer(typeof(List<Book>));
        var books = serializer.Deserialize(stream) as List<Book>;

        stream.Close();

#if WINDOWS_PHONE
        store.Dispose();
#endif

        return books;
    }

    private void SaveNewBook(List<Book> books, Book book)
    {
        books.Add(book);
        #if WINDOWS_PHONE
                IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication();
                IsolatedStorageFileStream stream = store.OpenFile("list.xml", FileMode.OpenOrCreate, FileAccess.ReadWrite);
        #else
	            FileStream stream = File.Open(FileName, FileMode.Create);			
        #endif
                XmlSerializer serializer = new XmlSerializer(typeof(List<Book>));                
                serializer.Serialize(stream, books);
                stream.Close();

        #if WINDOWS_PHONE
                store.Dispose();
        #endif
    }

  }
}
